/*
 * ResourceDAO.java
 *
 * $Id: ResourceDAO.java,v 1.2 2009-03-02 15:31:23 mario Exp $
 *
 * Author: Mario García García - Imagos 2007
 */
package org.ceteca.explica.server.installer;

import java.util.ArrayList;
import java.util.List;

import org.ceteca.explica.core.InterfaceErrors;
import org.ceteca.explica.core.installer.AreaOT;
import org.ceteca.explica.core.installer.ResourceException;
import org.ceteca.explica.core.installer.ResourceOT;
import org.ceteca.explica.server.util.db.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 * This class implements the application resources data access object. It's 
 * a part of the data access layer and gives access to the database data. 
 * It knows the database structure and implementation. 
 * <br/>
 * This class is implemented to access a PostgreSQL database implementation.
 * <br/>
 * Responsibilities:
 * <li>
 * 	<ul> Provide statements for inserting new application resources into the database. </ul>
 *  <ul> Provide statements for updating application resources into the database. </ul>
 *  <ul> Provide statements for deleting application resources from the database. </ul>
 *  <ul> Provide the database queries needed for application resources.  </ul>
 * </li>
 */

public class ResourceDAO {
	public ResourceDAO() {
	}
	
	/**
	 * Query the database to get all the application resources available. 
	 * @throws ResourceException, in case any error take place during
	 * the query operation.
	 * @return ArrayList, list of all the application resources.
	 */
	public List getAllResources() throws ResourceException {
		List result = new ArrayList();
		// Open a new Hibernate session to query the Database
		Session session = HibernateUtil.getSessionFactory().openSession();

        try {
        	// Load the objects
        	result = session.createQuery(
            "from ResourceOT r")
            .list();

            System.out.println( "Consulta realizada! " +
            		result == null || result.size() <= 0?(" No se ha encontrado ningún recurso!"):
            		("Se han encontrado: " + result.size() + " recursos"));
        }
        catch (HibernateException ex) {
        	System.err.println("No se puede realizar la consulta a la BD!");
        	ex.printStackTrace();
        	throw new ResourceException(InterfaceErrors.ERR_RESOURCE_NOT_FOUND);
        }
        
        // Close the Hibernate session
        session.close();	
        
        // Return the result of the query
        return result;
	}
	
	/**
	 * Query (by primary key) the database to get an application resource data. 
	 * @param idResource long, Internal id of the application resource.
	 * @throws ResourceException, in case any error take place during
	 * the query operation.
	 * @return ResourceOT, application resource if it exists, null in 
	 * any other case.
	 */
	public ResourceOT getResource(long idResource) throws ResourceException {
		ResourceOT result = null;
		// Open a new Hibernate session to query the Database
		Session session = HibernateUtil.getSessionFactory().openSession();

        try {
        	// Load the object by the primary key (idResource)
        	result = (ResourceOT)session.get(ResourceOT.class, new Long(idResource));

            System.out.println( "Consulta realizada! " +
            		result == null?(" No se ha encontrado ningún recurso correspondiente!"):
            		("Se ha encontrado el recurso: " + result.getDescription()));
        }
        catch (HibernateException ex) {
        	System.err.println("No se puede realizar la consulta a la BD!");
        	ex.printStackTrace();
        	throw new ResourceException("" + idResource, InterfaceErrors.ERR_RESOURCE_NOT_FOUND);
        }
        
        // Close the Hibernate session
        session.close();	
        
        // Return the result of the query
        return result;
	}
	
	/**
	 * Query the database to get an application resource data. 
	 * @param codResource String, External code of the application resource.
	 * @throws ResourceException, in case any error take place during
	 * the query operation.
	 * @return ResourceOT, application resource if it exists, null in 
	 * any other case.
	 */
	public ResourceOT getResource(String codResource) throws ResourceException {
		ResourceOT result = null;
		// Open a new Hibernate session to query the Database
		Session session = HibernateUtil.getSessionFactory().openSession();

        try {
        	// Build the query statement
        	String sql = "FROM ResourceOT r WHERE r.codResource=?";
        	Query q = session.createQuery(sql);
        	q.setString(0, codResource);

        	// Run the query statement
        	result = (ResourceOT)q.uniqueResult();

            System.out.println( "Consulta realizada! " +
            		result == null?(" No se ha encontrado ningún recurso correspondiente!"):
            		("Se ha encontrado el recurso: " + result.getDescription()));
        }
        catch (HibernateException ex) {
        	System.err.println("No se puede realizar la consulta a la BD!");
        	ex.printStackTrace();
        	throw new ResourceException("" + codResource, InterfaceErrors.ERR_RESOURCE_NOT_FOUND);
        }
        
        // Close the Hibernate session
        session.close();	
        
        // Return the result of the query
        return result;
	}
	
	/**
	 * Return the areas' list including the list of all the modules
	 * belonging to each area.
	 * @return List, list of areas.
	 * @throws ResourceException in case any error take place during the
	 * query operation.
	 */
	public List getAllAreas() throws ResourceException {
		List result = new ArrayList();
		// Open a new Hibernate session to query the Database
		Session session = HibernateUtil.getSessionFactory().openSession();

        try {
        	// Build the query statement
        	String sql = "FROM AreaOT a";
        	Query q = session.createQuery(sql);

        	// Run the query statement
        	result = q.list();
       	
        	// For each area get the list of modules available
        	for (int i=0; result != null && i<result.size(); i++) {
        		((AreaOT)result.get(i)).setLModules((ArrayList)this.getAreaModules(((AreaOT)result.get(i)).getIdArea()));
        	} // for each area
	        
            System.out.println( "Consulta realizada! " +
            		result == null || result.size() <= 0?(" No se ha encontrado ningún área!"):
            		("Se han encontrado: " + result.size() + " areas"));
        }
        catch (HibernateException ex) {
        	System.err.println("No se puede realizar la consulta a la BD!");
        	ex.printStackTrace();
        	throw new ResourceException(InterfaceErrors.ERR_AREA_NOT_FOUND);
        }
        
        // Close the Hibernate session
        session.close();	
        
        // Return the result of the query
        return result;
	}
	
	public List getAreaModules(String idArea) throws ResourceException {
		List result = new ArrayList();
		// Open a new Hibernate session to query the Database
		Session session = HibernateUtil.getSessionFactory().openSession();

        try {
        	// Build the query statement
        	String sql = "FROM ResourceOT r WHERE r.idArea=?";
        	Query q = session.createQuery(sql);
        	q.setString(0, idArea);

        	// Run the query statement
        	result = q.list();

            System.out.println( "Consulta realizada! " +
            		result == null || result.size() <= 0?(" No se ha encontrado ningún módulo!"):
            		("Se han encontrado: " + result.size() + " módulos"));
        }
        catch (HibernateException ex) {
        	System.err.println("No se puede realizar la consulta a la BD!");
        	ex.printStackTrace();
        	throw new ResourceException(InterfaceErrors.ERR_RESOURCE_NOT_FOUND);
        }
        
        // Close the Hibernate session
        session.close();	
        
        // Return the result of the query
        return result;
	}
	
	/**
	 * Returns tag Id assigned to CVS source file.
	 */
	public static String getRevision() {
		return "$Id: ResourceDAO.java,v 1.2 2009-03-02 15:31:23 mario Exp $";
	}
}
